package com.xpec.c4.service.ioc.cglib;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Set;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import com.xpec.c4.service.ioc.AOPMethodInterceptor;
import com.xpec.c4.service.ioc.LoggerInterceptor;
import com.xpec.c4.service.ioc.OutInterceptor;
import com.xpec.c4.service.ioc.ProxyType;

/**
 * Cglib的代理方法处理
 * 
 * @author lipeilin
 * 
 */
public class CglibCommonInterceptor implements MethodInterceptor,Serializable {
	
	private AOPMethodInterceptor[] mis;
	
	public CglibCommonInterceptor(Set<ProxyType> proxyTypes) {
		int index=0;
		mis=new AOPMethodInterceptor[proxyTypes.size()];
		if(proxyTypes.contains(ProxyType.OUT)){
			mis[index++]=new OutInterceptor();
		}
		if(proxyTypes.contains(ProxyType.LOGGER)){
			mis[index++]=new LoggerInterceptor();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.sf.cglib.proxy.MethodInterceptor#intercept(java.lang.Object,
	 * java.lang.reflect.Method, java.lang.Object[],
	 * net.sf.cglib.proxy.MethodProxy)
	 */
	@Override
	public Object intercept(Object object, Method method, Object[] args,
			MethodProxy methodProxy) throws Throwable {
		boolean flag;
		for(AOPMethodInterceptor mi:mis){
			flag=mi.beforeMethod(object, method, args);
			if(flag==false){
				return null;
			}
		}
		Object result = methodProxy.invokeSuper(object, args);
		for(AOPMethodInterceptor mi:mis){
			mi.afterMethod(object, method, args);
		}
		return result;
	}

}
